'''
命令路由
'''
import os
from sqlite3.dbapi2 import Connection
from typing import List
import database
from colorama import init, Fore, Back, Style
import const

WORD_MAX_SIZE = 40


def router(connection: Connection, input: str):
    init(autoreset=True)
    if input.startswith(const.CLEAR):
        os.system('cls')
    elif input.startswith(const.QUIT):
        exit(1)
    elif input.startswith(const.HELP):
        print(Fore.RED+"葡萄翻译命令提示:\n\t-c   清空\n\t-q   退出\n\t-h   帮助\n\t-s   以字符串开始的单词\n\t-e   以字符串结尾的单词\n\t-a   与该字符串全匹配的单词\n\t-p   在单词解释中搜索该字符串")
    elif not input.startswith(const.COMMAND_PREFIX):
        show(database.list(connection, input), input)
    elif input.startswith(const.ALL):
        input = input.strip()[3:]
        show(database.list_by_word_all(connection, input), input)
    elif input.startswith(const.START):
        input = input.strip()[3:]
        show(database.list_by_word_star(connection, input), input)
    elif input.startswith(const.END):
        input = input.strip()[3:]
        show(database.list_by_word_end(connection, input), input)
    elif input.startswith(const.EXPLAIN):
        input = input.strip()[3:]
        show(database.list_by_explain(connection, input), input)
    else:
        print(Fore.RED+"输入格式不规范 '> - <'  !!!")


def show(rows: List[str], input: str):
    init(autoreset=True)
    if(len(rows) > 0):
        for row in rows:
            word = row[0]
            if word == None:
                word = ' '
            word = word.strip()
            explain = row[1]
            if explain == None:
                explain = ' '
            explain = explain.strip()
            # 空格数
            empty_str = ''
            for _ in range(WORD_MAX_SIZE-len(word)):
                empty_str += ' '
            print(highlightHandler(word, input)+empty_str +
                  highlightHandler(explain, input))
    else:
        print(Fore.RED+"未检索到相关数据 '> - <'  !!!")


def highlightHandler(info: str, input: str) -> str:
    res = info
    if input in info:
        res = info.replace(input, Fore.LIGHTYELLOW_EX+input+Fore.LIGHTCYAN_EX)
    return Fore.LIGHTCYAN_EX+res
